#include <arpa/inet.h>
#include <gtest/gtest.h>
#include <thread>
#include <chrono>
#include <string>
#include <cstring>
#include <netinet/in.h>
#include <unistd.h>
#include "eventloop.h"
#include "tcpserver.h"
#include "tcpconnection.h"

TEST(TcpServerIntegrationTest, EchoServer) {
    EventLoop loop;
    TcpServer server(&loop, "127.0.0.1", 9999);

    // 注册回显逻辑
    server.setMessageCallback([](const std::shared_ptr<TcpConnection>& conn, const std::string& msg) {
        conn->send(msg);  // 回显
    });

    // 启动服务线程
    std::thread serverThread([&]() {
        server.start();
        loop.loop();
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(200)); // 确保服务启动

    // ---- 客户端连接服务器 ----
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    ASSERT_GT(sockfd, 0);

    sockaddr_in servAddr{};
    servAddr.sin_family = AF_INET;
    servAddr.sin_port = htons(9999);
    inet_pton(AF_INET, "127.0.0.1", &servAddr.sin_addr);

    ASSERT_EQ(connect(sockfd, (sockaddr*)&servAddr, sizeof(servAddr)), 0);

    // ---- 发送并接收消息 ----
    const std::string sendMsg = "hello server";
    ::write(sockfd, sendMsg.c_str(), sendMsg.size());

    char buf[1024] = {0};
    ssize_t n = ::read(sockfd, buf, sizeof(buf));
    ASSERT_GT(n, 0);
    std::string recvMsg(buf, n);

    EXPECT_EQ(sendMsg, recvMsg);

    // ---- 清理 ----
    ::close(sockfd);
    loop.quit();           // 结束事件循环
    serverThread.join();   // 等待服务退出
}
